package edu.ucla.cs.rpc.multicast.util.token;

import java.io.Serializable;
import java.util.*;

import edu.ucla.cs.rpc.multicast.network.message.*;

/**
 * A Token is an object that provides non-refutable permission to perform some
 * sort of operation. For our purposes, the operation is to multi-cast messages.
 * 
 * @author Philip Russell Chase Covello
 * 
 */
public class Token implements Serializable {
	
	private static final long serialVersionUID = 1L;

	/* Sequence number to enforce total order amongst messages */
	private long seqNum;

	/* The set of messages that have already been sequenced */
	private Set<Message> sequenced;

	/**
	 * Initializes the sequence number and set of sequenced messages.
	 * 
	 */
	public Token() {
		this.seqNum = 0;
		sequenced = new HashSet<Message>();
	}

	/**
	 * 
	 * @return An unused sequence number.
	 */
	public long getSeqNum() {
		return this.seqNum;
	}

	/**
	 * 
	 * @param val
	 */
	public void setSeqNum(long val) {
		this.seqNum = val;
	}

	/**
	 * Attempts to add a message to the queue of messages that have already been
	 * sequenced. If the message is already contained in the set, this method
	 * throws an exception to indicate this.
	 * 
	 * @param m
	 *            Message to add to the queue of sequenced messages.
	 * @throws DuplicateEntryException
	 *             Exception thrown when attempting to add a non-unique message
	 *             to the queue.
	 */
	public void addMessage(Message m) throws DuplicateEntryException {
		if (this.sequenced.add(m) == false) {
			throw new DuplicateEntryException("RPCMessage argument m = "
					+ m.toString());
		}
	}

}
